<html>
    <head>
        <title>client side caching</title>
        <script type="text/javascript" src="javascript/gears_init.js"></script>
        <script type="text/javascript" src="javascript/sample.js"></script>
		<script src="javascript/prototype.js"></script>
		<script src="javascript/jt_ProgressBar.js"></script>
		<script language="javascript">
    /**
     * Creates an HTTP GET request and sends the response to the callback function
     */
    function HTTPGet(uri, callbackFunction, callbackParameter) {
      var xmlHttp = new XMLHttpRequest();
      var bAsync = true;
      if (!callbackFunction)
        bAsync = false;
      xmlHttp.open('GET', uri, bAsync);
      xmlHttp.send(null);
      if (bAsync) {
        if (callbackFunction) {
          xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4){
                callbackFunction(xmlHttp.responseText, xmlHttp, callbackParameter)
            }
          }
        }
        return true;
      }
      else {
        return xmlHttp.responseText;
      }
    }
    var s_query;
    function getQuery(str)
    {
      var url="getQuery.php";
      url=url+"?q="+str;
      url=url+"&sid="+Math.random();

      return HTTPGet(url);
    }

    </script>

		<style>
			.bgBar {
				background: #00008b;
				border: 1px solid #FFFFFF;
				color: #FFFFFF;
			}

			.bgBarRed {
				background: #ff0000;
				border: 1px solid #FFFFFF;
				color: #FFFFFF;
				font-weight : bold;
			}
		</style>

		<script language="javascript">
		    var db;
		    var totalTables = 1;
		    var googleGearInstalled = false;
		    var googleGearGivenPermission = false;

			var totalThreadsDbSync = 1;
			var workerPoolDbSync = null;
			var childWpArrayDbSync = new Array(totalThreadsDbSync);

			var overallProgressCounter = 0;
			var currentProgressCounter = 0;
			var overallProgressEndCounter = totalTables;
			var currentProgressEndCounter = 0;
			var currentSyncTableName = "";

			var overAllProcessCounterDisplayObject;
			var currentProcessCounterDisplayObject;


//			var ganttData = eval(["INSERT INTO eddy_gantt (id, wbs_name, wbs_days, wbs_position, wbs_progress, wbs_order, project_id) VALUES(1, 'Project Setup', 2, 0, 100, 1, 1)","INSERT INTO eddy_gantt (id, wbs_name, wbs_days, wbs_position, wbs_progress, wbs_order, project_id) VALUES(2, 'Project Allocation', 2, 40, 10, 2, 1)"]);
          var qry_eddy_gantt = getQuery('eddy_gantt');
          var qry_eddy_gantt_arr = qry_eddy_gantt.split("~*~");
          var ganttData = Array();
          for(i=0;i<qry_eddy_gantt_arr.length;i++){
            ganttData[ganttData.length] = qry_eddy_gantt_arr[i];
        	}



		    function init()
		    {
		  		if (!window.google || !google.gears) {
		    		return;
		  		}
		  		googleGearInstalled = true;

		        try {
		            db = google.gears.factory.create('beta.database', '1.0');
		        	googleGearGivenPermission = true;
		        } catch (ex) {
		        	googleGearGivenPermission = false;
		            //setError('Could not create database: ' + ex.message);
		        }

		        if (db) {
					console.log("here");
		            db.open('gantt-db');
					console.log("1");
					db.execute("DROP TABLE IF EXISTS  eddy_gantt");
		            createTables();
		            workerpoolDbSyncInit();
		        }

				overAllProcessCounterDisplayObject = new jt_ProgressBar(document.getElementById("overallProgressBarElement"), 350, 30, "bgBarRed");
				currentProcessCounterDisplayObject = new jt_ProgressBar(document.getElementById("currentProgressBarElement"), 350, 30, "bgBar");
		    }




		    function createTables()
		    {
				db.execute('CREATE TABLE IF NOT EXISTS eddy_gantt (id INTEGER PRIMARY KEY ,wbs_name varchar(30),wbs_days int,wbs_position int,wbs_progress int,wbs_order int,project_id int)');
		    }


			function workerpoolDbSyncInit()
			{
				try
				{
					workerPoolDbSync = google.gears.factory.create('beta.workerpool', '1.0');
		        	googleGearGivenPermission = true;
				}
				catch (ex)
				{
					googleGearGivenPermission = false;
				  	//document.getElementById('asyncButton').disabled = true;
				  	//setError('Could not create worker pool: ' + ex.message);
				  	return;
				}

		  		//set the parent's message handler
		  		workerPoolDbSync.onmessage = parentHandlerDbSync;

		  		//setup the entire body of JavsScript code to run in the worker
		  		var childCode = String(childInitDbSync) +
		                  		String(childHandlerDbSync) +
		                  		'childInitDbSync();';  // runs init function

		  		//create the worker
		  		try
		  		{
		   			for (var i=0; i < totalThreadsDbSync; i++)
		   			{
			   			childWpArrayDbSync[i] = workerPoolDbSync.createWorker(childCode);
		   			}
		  		}
		  		catch (e)
		  		{
		  			googleGearGivenPermission = false;
		   			//setError('Could not create worker: ' + e.message);
		  		}
			}

			function parentHandlerDbSync(msg, sender)
			{
				var per;

		  		currentProgressCounter = currentProgressCounter + 1;
		  		per = Math.round((currentProgressCounter/currentProgressEndCounter) * 100);
		  		currentProcessCounterDisplayObject.setPercent(per);

		  		$("currentProgressRecordStatus").innerHTML = "Record : <b>" + currentProgressCounter + "</b> of <b>" + currentProgressEndCounter + "</b>";
		  		$("currentProgressTableStatus").innerHTML = "Table : <b>" + currentSyncTableName + "</b>";

		  		if (currentProgressCounter >= currentProgressEndCounter)
		  		{
		  			overallProgressCounter = overallProgressCounter + 1;
		  			per = Math.round((overallProgressCounter/overallProgressEndCounter) * 100);
		  			overAllProcessCounterDisplayObject.setPercent(per);

					if(per=="100"){
						document.frm.cont_button.disabled=false;
					}
				}
			}

			function childInitDbSync()
			{
		  		_workerDbHandle = google.gears.factory.create('beta.database', '1.0');
		  		_workerDbHandle.open('gantt-db');

				//_workerDbHandle.execute("delete from phone");
		  		gearsWorkerPool.onmessage = childHandlerDbSync;
			}


			function childHandlerDbSync(msg, sender)
			{
				_workerDbHandle.execute(msg);
		  		gearsWorkerPool.sendMessage(String(msg), sender);
			}

			function tableSync(tableName, json)
			{
		 		currentProgressCounter = 0;
		 		currentSyncTableName = tableName;

		        var jsonData = eval(json);
				currentProgressEndCounter = jsonData.length;

				var threadctr = 0;
		        for (var i=0; i < jsonData.length; i++) {
		        	sql = jsonData[i];

					workerPoolDbSync.sendMessage(sql, childWpArrayDbSync[threadctr]);

					threadctr = threadctr + 1;
					if (threadctr >= totalThreadsDbSync) {
						threadctr = 0;
					}
		        }
			}

			function startDbSyncProcess()
			{
		  		if (workerPoolDbSync) {
		  			db.execute('delete from eddy_gantt');
		  			overallProgressCounter = 0;
		  			tableSync('Gantt',ganttData);
		  		} else {
		  			if (!googleGearInstalled) {
		  				alert("you have to install google gear to run this example\n\nvisit => http://gears.google.com/");
		  				return
		  			}
		  			if (!googleGearGivenPermission) {
		  				alert("You have to authorize this site to use Google Gear on your computer! press F5 and try again.");
		  				return;
		  			}
		  		}
			}
		</script>
    </head>
	<body onLoad="init()">
    <img src="../images/eddytools_trans.png">
		<h3>Google gear Quiz Attempt</h3>
		<p>&nbsp;</p>
<table width="100%">
			<tr>
				<td align="center" width="100%">
					<table border="1" cellpadding="15" cellspacing="3">
						<tr>
							<td width="355">
								<center>
									<b>Storing Data locally...</b>
								</center>
								<br/>

								<small>Total Progress</small>
								<br/>
								<div id="overallProgressBarElement"></div>
								<br/><br/>
								<small>Current Task</small>
								<br/>
								<div id="currentProgressBarElement"></div>
								<div id="currentProgressTableStatus"></div>
								<div id="currentProgressRecordStatus"></div>
							</td>
						</tr>
					</table>
				</td>
			</tr>
		</table>

		<br/><br/>
		<center>
        <form name="frm">
		<input type="button" id="asyncButton" value="Start DB Sync Process" onClick="startDbSyncProcess();">
        <input type="button"  disabled name="cont_button" value="Continue Exam" onClick="window.location.href='../attempt.php';">
        </form>
		</center>
		</body>
</html>
